<?php

	namespace org\tekuna\test\core;


	use \PHPUnit_Framework_TestCase;

	use org\tekuna\core\context\Context;
	use org\tekuna\core\event\Event;
	use org\tekuna\core\event\AbstractEventListener;
	use org\tekuna\core\event\EventManager;
	
	class EventManagerTest extends PHPUnit_Framework_TestCase {

		public function testEventsTrigger() {
			
			global $GLOBALS;
			$GLOBALS['TEKUNA_EVENTMANAGERTEST_FUNCTIONS'] = '';
			
			$objEM = new EventManager();
			$objEM -> setApplicationContext(new Context());
			$objEM -> registerListener(new TestEventListener1());
			$objEM -> registerListener(new TestEventListener2(), 5);
			$objEM -> registerListener(new TestEventListener3(), 'min');
			
			$objEM -> triggerEvent(new TestEvent1());
			$objEM -> triggerEvent(new TestEvent2());

			// what should happen:
			// listeners are sorted 3-2-1
			// listener 3 handles both events
			// listener 2 handles only event 2
			// listener 1 handles only event 1
			
			// event 1 triggered
			$sShouldBe .= "TEL3.hsE\n";
			$sShouldBe .= "TEL3.hE\n";
			$sShouldBe .= "TEL2.hsE\n";
			$sShouldBe .= "TEL1.hsE\n";
			$sShouldBe .= "TEL1.hE\n";
			
			// event 2 triggered
			$sShouldBe .= "TEL3.hsE\n";
			$sShouldBe .= "TEL3.hE\n";
			$sShouldBe .= "TEL2.hsE\n";
			$sShouldBe .= "TEL2.hE\n";
			$sShouldBe .= "TEL1.hsE\n";

			$this -> assertEquals($sShouldBe, $GLOBALS['TEKUNA_EVENTMANAGERTEST_FUNCTIONS']);
		}
	}

	
	class TestEvent1 implements Event {}
	class TestEvent2 implements Event {}
	
	class TestEventListener1 extends AbstractEventListener {
		
		public function handlesEvent(Event $objEvent) {
			
			global $GLOBALS;
			$GLOBALS['TEKUNA_EVENTMANAGERTEST_FUNCTIONS'] .= "TEL1.hsE\n";
			
			return $objEvent instanceof TestEvent1;
		}
		
		public function handleEvent(Event $objEvent) {
			
			global $GLOBALS;
			$GLOBALS['TEKUNA_EVENTMANAGERTEST_FUNCTIONS'] .= "TEL1.hE\n";
		}
	}
	
	class TestEventListener2 extends AbstractEventListener {
		
		public function handlesEvent(Event $objEvent) {
			
			global $GLOBALS;
			$GLOBALS['TEKUNA_EVENTMANAGERTEST_FUNCTIONS'] .= "TEL2.hsE\n";
			
			return $objEvent instanceof TestEvent2;
		}
		
		public function handleEvent(Event $objEvent) {
			
			global $GLOBALS;
			$GLOBALS['TEKUNA_EVENTMANAGERTEST_FUNCTIONS'] .= "TEL2.hE\n";
		}
	}
	
	class TestEventListener3 extends AbstractEventListener {
		
		public function handlesEvent(Event $objEvent) {
			
			global $GLOBALS;
			$GLOBALS['TEKUNA_EVENTMANAGERTEST_FUNCTIONS'] .= "TEL3.hsE\n";
			
			return true;
		}
		
		public function handleEvent(Event $objEvent) {
			
			global $GLOBALS;
			$GLOBALS['TEKUNA_EVENTMANAGERTEST_FUNCTIONS'] .= "TEL3.hE\n";
		}
	}